package com.fieldchain.ex.fa100.utils.common;

import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import com.fieldchain.ex.fa100.R;
import com.fieldchain.ex.fa100.access.MyApplication;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/8/20
 */
public class VerticalUtils {
    private static VerticalUtils ver;
    private TextView tv;
    private Timer timer ;
    private int tags=60;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if(tags>0) {
                        tv.setText(tags + "s");
                        tags--;
                    }else{
                        tv.setClickable(true);
                        timer.cancel();
                        tv.setText(MyApplication.getAppContext().getResources().getText(R.string.get_code));
                        tv.setTextColor(Color.parseColor("#0090f7"));
                    }
                    break;
            }
        }
    };
    private VerticalUtils (){

    }

    public void stop(){
        tv.setClickable(true);
        if(timer!=null){
            timer.cancel();
        }
        mHandler.removeCallbacksAndMessages(null);
        if(tv!=null){
            tv.setTextColor(Color.parseColor("#0090f7"));
            tv.setText(MyApplication.getAppContext().getResources().getText(R.string.get_code));
        }
    }
    public static VerticalUtils getInstance() {
        if (null == ver) ver = new VerticalUtils();
        return ver;
    }


    public void start(TextView tv){
        tags=60;
        this.tv=tv;
        tv.setClickable(false);
        tv.setTextColor(Color.parseColor("#dddddd"));
        startTimer();

    }

    public void cancle(){
        if(timer!=null) {
            timer.cancel();
        }
        if(tv!=null&&tv.getContext()!=null){
            tv.setText(MyApplication.getAppContext().getResources().getText(R.string.get_code));
        }
        tv=null;
        timer=null;
    }
    private void startTimer(){
        if(timer!=null){
            timer=null;
        }
        timer=new Timer();
        TimerTask task=new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(task,0,1000);
    }
}
